/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
		'pageInit',
		'multiFormValidator',
    'formAjax',
    'notification',
    'select2',
    'holder',
    'uploadFiles',
    'dateRange',
    'moment'
	], function ($, vamakerPage, multiFormValidator, formAjax, VamOpMsg, select2, holder, UploadFiles, DateRange, moment) {
  $(function () {
    var $importOpBtn = $('#import-operate-btn'),
      importUrl = VAM.getVar('DATA_IMPORT_URL');
    // Init data import.
    var $uploadMaterial = $('#import-operate-btn'),
      $uploadMaterialModal = $('#upload-material-modal'),
      $uploadMaterialOperate = $('#upload-confirm-operate');

    $uploadMaterialModal.on('hidden.bs.modal', function (evt) {
      var $me = $(this);
      $('#progress .progress-bar').css('width','0%').text('0%');
      $('#files').find('tbody').html('');
    });

    $uploadMaterial.on('click', function (evt) {
      var $me = $(this);
      $uploadMaterialModal.modal('show');
    });
    
    $uploadMaterialOperate.on('click', function(evt) {
      var $me = $(this),
        importStatus = $me.data('importStatus');
      evt.preventDefault();
      // console.log(importStatus);
      $me.data('importStatus', '');
      $uploadMaterialModal.modal('hide');
      if (importStatus !== '') {
        // dataList.ajax.reload();
      }
    });
  });
  // Upload Creative Material.
  $(function () {
      'use strict';
      var url = VAM.getVar('DATA_IMPORT_URL'),
          $fileUpload = $('#fileupload'),
          $progressBar = $('#progress .progress-bar'),
          $table = $('#files').find('table tbody'),
          $modalLoadingWrap = $('#modal-loading-wrap');
      
      // VAM.fn.loadingSpinner($modalLoadingWrap);

      $fileUpload.fileupload({
          url: url,
          dataType: 'json',
          beforeSend: function() {
            $modalLoadingWrap.show();
          },
          done: function (e, data) {
            $modalLoadingWrap.hide();
            if (data.result.status === 'success') {
              var materialData = data.result.data,
               list = materialData['table'],
               listStr = '';
              console.log(materialData);
              VAM.fn.Messenger(data.result.msg, 'success');
              $.each(list, function(index, ele) {
                var str = '';
                str += '<tr>'
                      + '<td>' + ele.name + '</td>'
                      + '<td>' + ele.size + '</td>'
                      + '<td>' + ele.date + '</td>'
                      + '<td>' + ele.judgeInfo + '</td>'
                      + '<td>' + ele.updater + '</td>'
                      + '</tr>';
                listStr += str;
              });
              $table.append(listStr);
              $('#upload-confirm-operate').data('importStatus', 'true');
            }else {
              VAM.fn.Messenger(data.result.reason, 'error');
              $('#upload-confirm-operate').data('importStatus', '');
            };
          },
          progressall: function (e, data) {
              var progress = parseInt(data.loaded / data.total * 100, 10);
              $progressBar.css('width','0%').text('0%');
              $progressBar.css(
                  'width',
                  progress + '%'
              ).text(progress + '%');
          }
      })
      .prop('disabled', !$.support.fileInput)
      .parent().addClass($.support.fileInput ? undefined : 'disabled')
      .on('fileuploadstart', function (evt) {
        console.log('before');
        $modalLoadingWrap.show();
      });
  });

  // get creative info
  $(function() {
    var dataFieldRule, options, dataValidator,
        formValidator = new multiFormValidator(),
        $dataFrm = $('#get-creative-form'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        $creativeInfo = $('#creative_info');
      dataFieldRule = {
        creative_id:{
          rule:{
            required:{
              message:'创意ID不能为空'
            }
          },
          messageContainer:'creative_id_err'
        }
      };
      
      options = {
        submitOnSucceed: false,
        onvalidate: function (evt) {
          if (evt.resultList.length <= 0) {
            $dataFrm.ajaxSubmit({
              beforeSubmit: function () {
                $submitBtn.button('loading');
              },
              success: function (data) {
                $submitBtn.button('reset');
                $creativeInfo.text(data.data);
              }
            });
          }
        }
      };
      formValidator.validate($dataFrm, dataFieldRule, options);
  });
  // solution import
  $(function() {
    var dataFieldRule, options, dataValidator,
        formValidator = new multiFormValidator(),
        $dataFrm = $('#solution-import-form'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        $rangeDateBtn = $('#range-date-btn'),
        $rangeDate = $('#range_date'),
        dateRange = new DateRange(),
        selectDate;
      dateRange.dateRange(
        $rangeDateBtn, {
          singleDatePicker: true,
        }, function (start, end, label) {
          selectDate = start.format('YYYY-MM-DD');
          $rangeDate.val(selectDate).trigger('blur');
      });
      dataFieldRule = {
        solution_id:{
          rule:{
            required:{
              message:'策略ID不能为空'
            }
          },
          messageContainer:'solution_id_err'
        },
        cost:{
          rule:{
            required:{
              message:'花费不能为空'
            },
            negfloatnumber:{
              message:'只能输入整数或浮点数'
            },
            effectiveNumber:{
              message: '保留两位有效数字'
            }
          },
          messageContainer:'cost_err'
        },
        show:{
          rule:{
            required:{
              message:'曝光不能为空'
            },
            intnumber:{
              message: '只能输入整数'
            },
          },
          messageContainer:'show_err'
        },
        click:{
          rule:{
            required:{
              message:'点击不能为空'
            },
            intnumber:{
              message: '只能输入整数'
            },
          },
          messageContainer:'click_err'
        },
        range_date: {
          rule: {
            required: {
              message: '日期不能为空'
            }
          },
          messageContainer: 'range_date_err'
        }
      };
      
      options = {
        submitOnSucceed: false,
        onvalidate: function (evt) {
          if (evt.resultList.length <= 0) {
            $dataFrm.ajaxSubmit({
              beforeSubmit: function () {
                $submitBtn.button('loading');
              },
              success: function (data) {
                $submitBtn.button('reset');
                VamOpMsg.messager(data);
              }
            });
          }
        }
      };
      formValidator.validate($dataFrm, dataFieldRule, options);
      dataValidator = formValidator.dataValidator;
      dataValidator.addRule('effectiveNumber',function(val, opt){
        return !!(val && /^[+-]?\d+(\.\d{1,2})?$/.test(val));
      });
  });
});
